
package com.kugou.game.sdk.ui.fragment;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.MobilePayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.interfaces.OnCardPayListener;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.dialog.MobileRechargeConfirmDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog;
import com.kugou.game.sdk.ui.dialog.SelectOptionDialog.OnSelectOptionListener;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.UUID;

/**
 * 描述:点卡充值界面
 *
 * @author wcj
 * @since 2015年11月3日 下午3:16:06
 */
public class RechargeByGameCardFragment extends BaseRechargeFragment implements OnClickListener {

    private final int PLATFORM = 0;

    private final int VALUE = 1;

    private static final int GAME_CARD_TYPE_JUNWANG = 0;

    private static final int GAME_CARD_TYPE_ZHENGTU = 1;

    private static final int GAME_CARD_TYPE_WANGYI = 2;

    private static final int GAME_CARD_TYPE_SHENGDA = 3;

    /**
     * 请求支付
     */
    private final int MSG_BACK_REQUEST_PAY = 1;

    /**
     * 请求支付成功
     */
    private final int MSG_PAY_SUCCESS = 2;

    /**
     * 请求支付失败
     */
    private final int MSG_PAY_FAILED = 3;

    private Context mContext;

    private static String[] platfroms = {
            "骏网一卡通", "征途游戏卡", "网易一卡通", "盛大一卡通"
    };

    private int[] zhengtuMoneys = {
            10, 20, 30, 50, 100, 300
    };

    private int[] junwangMoneys = {
            10, 30, 50, 100, 200, 300
    };

    private int[] wangyiMoneys = {
            10, 30, 50, 100, 300, 500, 1000
    };

    private int[] shengdaMoneys = {
            10, 30, 50, 100, 300, 500, 1000
    };

    private int[] cardNumCounts = {
            16, 16, 13, 15
    };

    private int[] cardPasswdCounts = {
            16, 8, 9, 8
    };

    // 当前选择的点卡类型
    private int mPhoneCardType = 0;

    // 当前选择的点卡金额位置
    private int mRechargeValueIndex = 0;

    /**
     * 保存用户选中的要进行兑换的值
     */
    private int mRechargeValue = 10;

    private String mOrderId;

    private TextView mRechargeErrorTipsTV;

    private Button mRechargeRatioBtn, mRechargePlatformBtn, mRechargeValueBtn, mRechargeSubmitBtn;

    private EditText mGameCardSNCodET, mGameCardPasswdET;

    public static RechargeByGameCardFragment getFragment(boolean rechargeYoubi) {
        RechargeByGameCardFragment fragment = new RechargeByGameCardFragment();
        fragment.mIsRechargeYoubi = rechargeYoubi;
        return fragment;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        initViews();
        updateCanGotKubi();
        updateViewByCartType(mPhoneCardType);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int layoutId = Rx.layout.kg_fragment_recharge_game_card;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_fragment_recharge_game_card_land;
        }
        return inflater.inflate(layoutId, null);
    }

    private void initViews() {
        mRechargeRatioBtn = (Button) findViewById(Rx.id.kg_btn_recharge_ratio);
        mRechargeRatioBtn.setOnClickListener(this);

        mRechargePlatformBtn = (Button) findViewById(Rx.id.kg_btn_recharge_platform);
        mRechargePlatformBtn.setOnClickListener(this);

        mRechargeValueBtn = (Button) findViewById(Rx.id.kg_btn_recharge_value);
        mRechargeValueBtn.setOnClickListener(this);

        mRechargeSubmitBtn = (Button) findViewById(Rx.id.kg_btn_recharge_submit);
        mRechargeSubmitBtn.setOnClickListener(this);

        mRechargeErrorTipsTV = (TextView) findViewById(Rx.id.kg_tv_recharge_mobile_error_tips);

        mGameCardSNCodET = (EditText) findViewById(Rx.id.kg_et_recharge_mobile_sn_code);
        mGameCardSNCodET.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    mGameCardSNCodET.setBackgroundResource(Rx.drawable.kg_shape_frame_blue);
                } else {
                    mGameCardSNCodET.setBackgroundResource(Rx.drawable.kg_shape_frame_gray);
                }

                mGameCardSNCodET.setPadding((int) (12 * getActivity().getResources()
                        .getDisplayMetrics().density), 0, 0, 0);
            }
        });

        mGameCardPasswdET = (EditText) findViewById(Rx.id.kg_et_recharge_mobile_passwd);
        mGameCardPasswdET.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    mGameCardPasswdET.setBackgroundResource(Rx.drawable.kg_shape_frame_blue);
                } else {
                    mGameCardPasswdET.setBackgroundResource(Rx.drawable.kg_shape_frame_gray);
                }

                mGameCardPasswdET.setPadding((int) (12 * getActivity().getResources()
                        .getDisplayMetrics().density), 0, 0, 0);
            }
        });

        mPhoneCardType = 0;
        mRechargeValueIndex = 0;
        mRechargeValue = 10;
    }

    private void updateCanGotKubi() {
        if (mIsRechargeYoubi) {
            updateCanGotKubiTextView(mRechargeValue, ChargeType.TYPE_GAME_CARD);
        }
    }

    // 更新卡号卡密输入框提示文字
    private void updateCardEditViewHint(int cardIndex) {
        if (cardIndex >= cardNumCounts.length)
            return;
        mGameCardSNCodET.setHint("请输入卡号（" + cardNumCounts[cardIndex] + "位）");
        mGameCardPasswdET.setHint("请输入卡密（" + cardPasswdCounts[cardIndex] + "位）");
    }

    @Override
    public void onClick(View v) {
        if (v == mRechargeRatioBtn) {
            showMessageDialog();
        } else if (v == mRechargePlatformBtn) {
            showOptionDialog(PLATFORM);
        } else if (v == mRechargeValueBtn) {
            showOptionDialog(VALUE);
        } else if (v == mRechargeSubmitBtn) {
            if (!checkAll()) {
                return;
            }

            showConfirmDialog();
            // 发送统计--点击确认支付按钮
            sendClickConfirmRechargeBtnStatics(ChargeType.TYPE_GAME_CARD, mRechargeValue);

        }
    }

    private void showConfirmDialog() {
        final MobileRechargeConfirmDialog dialog = new MobileRechargeConfirmDialog(getActivity());
        dialog.setRechargeInfo(
                platfroms[mPhoneCardType],
                mRechargeValue,
                mIsRechargeYoubi ? PayManager.getExchangeNum(mRechargeValue,
                        ChargeType.TYPE_GAME_CARD) : null);
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sendEmptyBackgroundMessage(MSG_BACK_REQUEST_PAY);
            }
        });
        dialog.show();
    }

    private void setEditTextFocus(EditText editText) {
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        editText.requestFocus();
        showSoftInput();
    }

    private boolean checkAll() {
        return checkCardNumber() && checkPasswordNumber() && checkCardNumCount();
    }

    private boolean checkCardNumber() {
        String text = mGameCardSNCodET.getText().toString();
        if (TextUtils.isEmpty(text)) {
            updateErrorTips("请输入正确的卡号");
            setEditTextFocus(mGameCardSNCodET);
            return false;
        }

        if (AppUtil.isCardNumberCorrect(text)) {
            return true;
        } else {
            updateErrorTips("充值卡号格式不正确");
            setEditTextFocus(mGameCardSNCodET);
            return false;
        }
    }

    private boolean checkPasswordNumber() {
        String text = mGameCardPasswdET.getText().toString();

        if (TextUtils.isEmpty(text)) {
            updateErrorTips("请输入正确的密码");
            setEditTextFocus(mGameCardPasswdET);
            return false;
        }

        if (AppUtil.isCardPasswordCorrect(text)) {
            return true;
        } else {
            setEditTextFocus(mGameCardPasswdET);
            updateErrorTips("密码格式不正确");
            return false;
        }
    }

    private boolean checkCardNumCount() {
        if (mPhoneCardType > cardNumCounts.length - 1) {
            return false;
        }

        String text = mGameCardSNCodET.getText().toString();
        if (text.length() != cardNumCounts[mPhoneCardType]) {
            updateErrorTips("请输入正确的卡号");
            setEditTextFocus(mGameCardSNCodET);
            return false;
        }

        text = mGameCardPasswdET.getText().toString();
        if (text.length() != cardPasswdCounts[mPhoneCardType]) {
            updateErrorTips("密码错误。请输入正确的密码");
            setEditTextFocus(mGameCardPasswdET);
            return false;
        }
        return true;
    }

    private void updateErrorTips(String tips) {
        mRechargeErrorTipsTV.setText("提示：" + tips);
        ToastUtil.showMsg(tips);
    }

    private void addOptions(ArrayList<String> options, int type) {
        if (mPhoneCardType == GAME_CARD_TYPE_JUNWANG) {
            addOptions(junwangMoneys, options);
        } else if (mPhoneCardType == GAME_CARD_TYPE_ZHENGTU) {
            addOptions(zhengtuMoneys, options);
        } else if (mPhoneCardType == GAME_CARD_TYPE_WANGYI) {
            addOptions(wangyiMoneys, options);
        } else if (mPhoneCardType == GAME_CARD_TYPE_SHENGDA) {
            addOptions(shengdaMoneys, options);
        }

    }

    private void addOptions(int[] values, ArrayList<String> options) {
        for (int i = 0; i < values.length; i++) {
            options.add(values[i] + "元");
        }
    }

    private void showOptionDialog(final int what) {
        SelectOptionDialog dialog = new SelectOptionDialog((Activity) mContext);
        ArrayList<String> options = new ArrayList<String>();

        if (what == PLATFORM) {
            dialog.setCurrentOptionIndex(mPhoneCardType);
            dialog.setDialogTitle("请选择充值方式");

            options.add(platfroms[0]);
            options.add(platfroms[1]);
            options.add(platfroms[2]);
            options.add(platfroms[3]);
        } else {
            dialog.setCurrentOptionIndex(mRechargeValueIndex);
            dialog.setDialogTitle("请选择点卡金额");

            addOptions(options, mPhoneCardType);
        }
        dialog.addDatas(options);

        dialog.setOnSelectOptionListener(new OnSelectOptionListener() {

            @Override
            public void afterSelectUser(String option, int index) {
                if (what == PLATFORM) {
                    updateViewByCartType(index);

                } else {
                    mRechargeValueIndex = index;
                    mRechargeValueBtn.setText(option);

                    if (mPhoneCardType == GAME_CARD_TYPE_JUNWANG) {
                        mRechargeValue = junwangMoneys[index];
                    } else if (mPhoneCardType == GAME_CARD_TYPE_ZHENGTU) {
                        mRechargeValue = zhengtuMoneys[index];
                    } else if (mPhoneCardType == GAME_CARD_TYPE_WANGYI) {
                        mRechargeValue = wangyiMoneys[index];
                    } else {
                        mRechargeValue = shengdaMoneys[index];
                    }
                }

                updateCanGotKubi();
            }
        });
        dialog.setDialogDefaultSize();
        dialog.show();

    }

    /**
     * 根据选择的卡类型更新界面
     * 
     * @param index
     */
    private void updateViewByCartType(int index) {
        mPhoneCardType = index;
        mRechargePlatformBtn.setText(platfroms[index]);

        mRechargeValueIndex = 0;
        if (mPhoneCardType == GAME_CARD_TYPE_ZHENGTU) {
            mRechargeValueBtn.setText(zhengtuMoneys[0] + "元");
            mRechargeValue = zhengtuMoneys[0];
        } else if (mPhoneCardType == GAME_CARD_TYPE_JUNWANG) {
            mRechargeValueBtn.setText(junwangMoneys[0] + "元");
            mRechargeValue = junwangMoneys[0];
        } else if (mPhoneCardType == GAME_CARD_TYPE_WANGYI) {
            mRechargeValueBtn.setText(wangyiMoneys[0] + "元");
            mRechargeValue = wangyiMoneys[0];
        } else {
            mRechargeValueBtn.setText(shengdaMoneys[0] + "元");
            mRechargeValue = shengdaMoneys[0];
        }

        updateCardEditViewHint(index);
    }

    private void showMessageDialog() {
        final BaseConfirmDialog dialog = new BaseConfirmDialog(getActivity());
        dialog.setCancelBtnVisibility(View.GONE);
        dialog.setOKBtnText("知道了");
        dialog.setOkBtnBackground(Rx.drawable.kg_selector_bottom_single_filleted_corner_retangle);
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.setDialogTitle("兑换比例");
        dialog.setMessage(PayManager.getRechargeExchangeTip(ChargeType.TYPE_GAME_CARD,
                mIsRechargeYoubi));
        dialog.show();
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }
        switch (msg.what) {
            case MSG_PAY_SUCCESS:
                hideLoadingView();
                if (getOnEventListener() != null) {
                    getOnEventListener().onCheckRechargeResult(msg.obj.toString(), mRechargeValue,
                            ChargeType.TYPE_GAME_CARD);
                }
                break;

            case MSG_PAY_FAILED:
                hideLoadingView();
                mRechargeErrorTipsTV.setText("提示：" + msg.obj.toString());
                ToastUtil.showMsg(msg.obj.toString());

                sendCancelRechargeStatics(ChargeType.TYPE_GAME_CARD, mRechargeValue, mOrderId, 1,
                        msg.obj.toString());
                break;

            default:
                break;
        }

    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        switch (msg.what) {
            case MSG_BACK_REQUEST_PAY:
                showLoadingView();
                payByGameCard();
                break;

            default:
                break;
        }
    }

    private void payByGameCard() {
        MobilePayRequestParams requestParams = new MobilePayRequestParams();

        // 1 骏网一卡通
        // 2 盛大一卡通
        // 3 网易一卡通
        // 4 征途游戏卡
        int cardtype = 1;
        if (mPhoneCardType == GAME_CARD_TYPE_JUNWANG) {
            cardtype = 1;
        } else if (mPhoneCardType == GAME_CARD_TYPE_ZHENGTU) {
            cardtype = 4;
        } else if (mPhoneCardType == GAME_CARD_TYPE_WANGYI) {
            cardtype = 3;
        } else if (mPhoneCardType == GAME_CARD_TYPE_SHENGDA) {
            cardtype = 2;
        }

        mOrderId = SDKControler.createNewOrderId();
        if (mIsRechargeYoubi) {
            // 生成唯一字符串
            mOrderId = UUID.randomUUID().toString();
            requestParams.setDirectCharge(0);
        } else {
            requestParams.setDirectCharge(1);
        }

        User user = UserManager.getInstance().getCurrentUserInternal();
        requestParams.setUserName(user.getAccountName());
        requestParams.setChargeType(ChargeType.TYPE_GAME_CARD);
        requestParams.setMoney(mRechargeValue * 100);
        requestParams.setOutOrderId(mOrderId);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setPhoneCardId(mGameCardSNCodET.getText().toString());
        requestParams.setPhoneCardPwd(mGameCardPasswdET.getText().toString());
        requestParams.setPhoneCardType(String.valueOf(cardtype));
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        PayManager.payByGameCard(requestParams, new OnCardPayListener() {

            @Override
            public void onSuccess(String orderId) {
                Message msg = new Message();
                msg.what = MSG_PAY_SUCCESS;
                msg.obj = orderId;
                sendUiMessage(msg);
            }

            @Override
            public void onFailed(String errorMsg) {
                Message msg = new Message();
                msg.what = MSG_PAY_FAILED;
                msg.obj = errorMsg;
                sendUiMessageDelayed(msg, 1000);
            }
        });
    }

}
